package com.starblink.android.basic.network.interceptor

import com.starblink.android.basic.network.base.BaseApiClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.log.SKLogger
import com.starblink.basic.util.CommUtils
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException

/**
 * Mock数据拦截器
 */
@Deprecated(message = "封装到base库")
class MockHttpInterceptor : Interceptor {
    companion object {
        const val TAG = "MockHttpInterceptor"
    }

    private val client = OkHttpClient.Builder()
        .addInterceptor(
            HttpLoggingInterceptor()
                .apply {
                    setLevel(HttpLoggingInterceptor.Level.BODY)
                }).build()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        // 生产环境 或者 Mock开关关闭，直接跳过
        if(BaseApiClient.isPub() || !com.starblink.android.charles.CharlesManager.isMockPacketInfo()){
            return chain.proceed(request)
        }

        var response: Response? = null
        var hasMockData: Boolean = false

        val call = client.newCall(
            Request.Builder()
                .url(
                    "http://172.16.83.215:8080/app/mockdata/getmockdata?deviceId=${
                        UserDataCenter.getDeviceId(
                            CommUtils.getContext()
                        )
                    }&apiName=${request.url.toString().substringAfterLast("/")}"
                )
                .get().build()
        )
        hasMockData = try {
            val mockResponse = call.execute()
            if (mockResponse.isSuccessful && (mockResponse.body?.contentLength() ?: 0) > 0) {
                SKLogger.e(TAG, "成功获取Mock数据")
                response = Response.Builder()
                    .body(mockResponse.body)
                    .request(chain.request())
                    .protocol(Protocol.HTTP_2)
                    .message("Mock")
                    .code(200)
                    .build()
                true
            } else {
                SKLogger.e(TAG, "获取Mock数据失败或无Mock数据")
                false
            }
        } catch (e: IOException) {
            e.printStackTrace()
            SKLogger.e(TAG, e.toString())
            false
        } catch (e: Exception) {
            e.printStackTrace()
            SKLogger.e(TAG, e.toString())
            false
        }

        if (!hasMockData) {
            response = chain.proceed(request)
        }
        return response!!
    }
}